package com.onetech.adrewards.free.fragments;

import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.analytics.tracking.android.Tracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.adapters.SlideFragmentAdapter;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.fragments.getpoints.AUFragment;
import com.onetech.adrewards.free.fragments.getpoints.AllFragment;
import com.onetech.adrewards.free.fragments.getpoints.AppliFreeFragment;
import com.onetech.adrewards.free.fragments.getpoints.GamesFragment;
import com.onetech.adrewards.free.fragments.getpoints.OthersFragment;
import com.onetech.adrewards.free.fragments.getpoints.RegisterFreeFragment;
import com.onetech.adrewards.free.models.AdRewardModel;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.SlideDTO;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.TabPageIndicatorCustom;
import com.zuzu.quickaction.ActionItem;
import com.zuzu.quickaction.QuickAction;
import com.zuzu.quickaction.QuickAction.OnActionItemClickListener;

public class GetPointsFragmentNewApi extends Fragment implements
		OnPageChangeListener, OnClickListener, OnActionItemClickListener {
	private View mView = null;
	private ViewPager mViewPager = null;
	private MyFragementAdapter mAdapter = null;
	private TabPageIndicatorCustom mIndicator;
	private View mPopupMenu=null;
	private QuickAction menu=null;
	private ImageView mDropDownIcon=null;
	protected Tracker mTracker;
	private ReloadDataAsync mReloadDataAsync=null;
	
	private View mSlideBannerContainer=null;
	
	private SlideFragmentAdapter mSlideAdapter=null;
	private CirclePageIndicator mSlideIndicatior=null;
	private ViewPager mSlideViewPager=null;
	private LoadSlideBanner mLoadSlideBanner=null;

	private static String[] CONTENT_TITLE = new String[6];

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			Context darkTheme = new ContextThemeWrapper(getActivity(),
					R.style.StyledIndicators);
			inflater = LayoutInflater.from(darkTheme);
			mView = inflater.inflate(
					R.layout.get_coin_fragement_new_api_layout, container,
					false);
			createTitleTabs();
			initView();
			initListener();
		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}
	private void createTitleTabs(){
		CONTENT_TITLE[0]=getString(R.string.menu_recommend);
		CONTENT_TITLE[1]=getString(R.string.menu_appli_cate);
		CONTENT_TITLE[2]=getString(R.string.menu_register_free_cate);
		CONTENT_TITLE[3]=getString(R.string.menu_au_cate);	
		CONTENT_TITLE[4]=getString(R.string.menu_others_cate);
		CONTENT_TITLE[5]=getString(R.string.menu_games_cate);
		
		
	}
	private void initView() {
		mSlideBannerContainer=(LinearLayout)mView.findViewById(R.id.slideContainer);
		
		mAdapter = new MyFragementAdapter(getChildFragmentManager());
		mViewPager = (ViewPager) mView.findViewById(R.id.fragmentPager);
		mViewPager.setOffscreenPageLimit(1);
		mViewPager.setAdapter(mAdapter);
		
		mIndicator = (TabPageIndicatorCustom) mView.findViewById(R.id.indicator);
		mIndicator.setViewPager(mViewPager);
		// switchMenuTabBackground(0);
		mIndicator.setOnPageChangeListener(this);
		
		
		mDropDownIcon=(ImageView)mView.findViewById(R.id.dropdownIcon);
		
		mPopupMenu=(LinearLayout)mView.findViewById(R.id.popup_menu_sort);
		
		
		menu=new QuickAction(getActivity());		
		ActionItem item1=new ActionItem(R.id.menu_recommend, getActivity().getString(R.string.menu_recommend));
		ActionItem item2=new ActionItem(R.id.menu_result, getActivity().getString(R.string.menu_result));
		ActionItem item3=new ActionItem(R.id.menu_new, getActivity().getString(R.string.menu_new));
		ActionItem item4=new ActionItem(R.id.menu_point, getActivity().getString(R.string.menu_point));
		ActionItem item5=new ActionItem(R.id.menu_no_sort, getActivity().getString(R.string.menu_no_sort));
		
		menu.addActionItem(item1);
		menu.addActionItem(item2);
		menu.addActionItem(item3);
		menu.addActionItem(item4);
		menu.addActionItem(item5);
		
		menu.changeActionItemSelectedBackgroud(AppConfig.AD_SORT, "#036AEA", "#FFFFFF", "#F1F1F1", "#036AEA");
		mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown_active);
		
		mIndicator.setCurrentItem(0);
	}	

	private void initListener() {
		mIndicator.setOnPageChangeListener(this);
		mPopupMenu.setOnClickListener(this);
		menu.setOnActionItemClickListener(this);
	}
	

	class MyFragementAdapter extends FragmentPagerAdapter {
		private BaseAdRewardFragment2 mCurrentFragment=null;
		
		public MyFragementAdapter(FragmentManager fm) {
			super(fm);
		}
		
		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), AllFragment.class
						.getName());
			case 1:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), AppliFreeFragment.class
						.getName());
			case 2:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), RegisterFreeFragment.class
						.getName());
			case 3:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), AUFragment.class
						.getName());
			
			case 4:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), OthersFragment.class
						.getName());
			case 5:
				return Fragment.instantiate(getActivity()
						.getApplicationContext(), GamesFragment.class
						.getName());
			
			default:
				return  Fragment.instantiate(getActivity()
						.getApplicationContext(), AllFragment.class
						.getName());
			}
			
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return CONTENT_TITLE[position % CONTENT_TITLE.length].toUpperCase();
		}

		@Override
		public int getCount() {
			return CONTENT_TITLE.length;
		}
		public Fragment getCurrentFragment() {
	        return mCurrentFragment;
	    }
	    @Override
	    public void setPrimaryItem(ViewGroup container, int position, Object object) {
	        if (getCurrentFragment() != object) {
	            mCurrentFragment = ((BaseAdRewardFragment2) object);
	        }
	        super.setPrimaryItem(container, position, object);
	    }
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		//switchMenuTabBackground(position);
		try {
			 if(mViewPager!=null){
				 mViewPager.setCurrentItem(position);
			 }
			if(mAdapter!=null && mAdapter.getCount()>position){				
				((BaseAdRewardFragment2)mAdapter.getCurrentFragment()).loadData();
			}
		} catch (Exception e) {
			
		}
	}
	
	private void showPopupMenu(View v) {								
		menu.show(v);
	}

	@Override
	public void onClick(View v) {
		int id=v.getId();
		switch (id) {
		case R.id.popup_menu_sort:
			showPopupMenu(v);
			break;		
		default:
			break;
		}
	}

	@Override
	public void onItemClick(QuickAction source, int pos, int actionId) {
		try {
			switch (actionId) {
			case R.id.menu_recommend:
				BaseAdRewardFragment2.mCurrentSortMenu=1;
				menu.changeActionItemSelectedBackgroud(0, "#036AEA", "#FFFFFF", "#F1F1F1", "#036AEA");
				mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown_active);
				break;
			case R.id.menu_result:
				BaseAdRewardFragment2.mCurrentSortMenu=2;
				menu.changeActionItemSelectedBackgroud(1, "#036AEA", "#FFFFFF", "#F1F1F1", "#036AEA");
				mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown_active);
				break;
			case R.id.menu_new:
				BaseAdRewardFragment2.mCurrentSortMenu=3;
				menu.changeActionItemSelectedBackgroud(2, "#036AEA", "#FFFFFF", "#F1F1F1", "#036AEA");
				mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown_active);
				break;
			case R.id.menu_point:
				BaseAdRewardFragment2.mCurrentSortMenu=4;
				menu.changeActionItemSelectedBackgroud(3, "#036AEA", "#FFFFFF", "#F1F1F1", "#036AEA");
				mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown_active);
				break;
			case R.id.menu_no_sort:
				BaseAdRewardFragment2.mCurrentSortMenu=5;
				menu.changeActionItemSelectedBackgroud(4, "#036AEA", "#FFFFFF", "#036AEA", "#FFFFFF");
				mDropDownIcon.setBackgroundResource(R.drawable.ic_btn_dropdown);
				break;
			default:
				break;
			}
			//((BaseAdRewardFragment)mAdapter.getCurrentFragment()).reloadListAdReward();
//			AdRewardModel.getInstance().clearAllData();
			((BaseAdRewardFragment2)mAdapter.getCurrentFragment()).loadData();	
			//reloadData();
			/*String name=((BaseAdRewardFragment)mAdapter.getCurrentFragment()).getmName();
			Toast.makeText(getActivity(), name, Toast.LENGTH_LONG).show();*/						
			
		} catch (Exception e) {
			return;
		}
	}
	@Override
	public void onResume() {
		super.onResume();
		if(mSlideAdapter ==null || (mSlideAdapter.mData!=null && mSlideAdapter.mData.size()<1)){
			loadSlideBannerHome();
		}
	}	
	private void reloadData(){
		if(mReloadDataAsync==null || mReloadDataAsync.getStatus()==Status.FINISHED){
			mReloadDataAsync=new ReloadDataAsync();
			mReloadDataAsync.execute();
		}
	}
	private class ReloadDataAsync extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			AdRewardModel.getInstance().clearAllData();
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			((BaseAdRewardFragment2)mAdapter.getCurrentFragment()).loadData();
		}
	}	
	private void loadSlideBannerHome(){
		if(mLoadSlideBanner==null || mLoadSlideBanner.getStatus()==Status.FINISHED){
			mLoadSlideBanner=new LoadSlideBanner();
			mLoadSlideBanner.execute();
		}
	}
	private class LoadSlideBanner extends AsyncTask<Void, Void, List<SlideDTO>>{

		@Override
		protected List<SlideDTO> doInBackground(Void... params) {
			return CommonModel.getInstance().getSliderBanner();
		}
		@Override
		protected void onPostExecute(List<SlideDTO> result) {
			super.onPostExecute(result);
			if(result!=null && result.size()>0){
				mSlideAdapter=new SlideFragmentAdapter(getActivity(), getChildFragmentManager(),result);
				mSlideViewPager=(ViewPager)mView.findViewById(R.id.slideViewPager);
				mSlideViewPager.setAdapter(mSlideAdapter);
				mSlideIndicatior=(CirclePageIndicator)mView.findViewById(R.id.slideIndicator);
				mSlideIndicatior.setViewPager(mSlideViewPager);
				mSlideBannerContainer.setVisibility(View.VISIBLE);
			}else{
				mSlideBannerContainer.setVisibility(View.GONE);
			}
		}
	}	
	public void switchFragmentViewPager(int index){		
		onPageSelected(index);
	}
}
